﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;

public class UploadService : IUploadService
{
    static Dictionary<Guid, string> _files = new Dictionary<Guid, string>();

    string fileDir = String.Format("{0}{1}{2}{1}", System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, Path.DirectorySeparatorChar, "App_Data");

    public Guid BeginUpload(string filename)
    {
        Guid key = Guid.NewGuid();
        _files.Add(key, filename);
        Directory.CreateDirectory(String.Format("{0}{1}", fileDir, key));
        return key;
    }

    public void UploadChunks(Chunk chunk)
    {
        using (FileStream fs = File.Create(String.Format("{0}{1}{2}{3}", fileDir, chunk.UploadKey, Path.DirectorySeparatorChar, chunk.Sequence)))
        {
            fs.Write(chunk.Data, 0, chunk.Data.Length);
        }
    }

    public void EndUpload(Guid key)
    {
        string filename = _files[key];
        DirectoryInfo di = new DirectoryInfo(String.Format("{0}{1}", fileDir, key));
        using (var fs = File.Create(Path.Combine(fileDir, filename)))
        {
            var files = di.GetFiles();
            foreach (var file in files.OrderBy(f => Int32.Parse(f.Name)))
            {
                using (var saved = file.OpenRead())
                {
                    byte[] buf = new byte[4096];
                    int numRead;
                    while ((numRead = saved.Read(buf, 0, 4096)) > 0)
                    {
                        fs.Write(buf, 0, numRead);
                    }
                }
            }
        }
        di.Delete(true);
    }
}
